package com.cysnake.quitsmoke.common.dao;

import java.text.ParseException;
import java.util.ArrayList;

import com.cysnake.quitsmoke.VO.CostVO;
import com.cysnake.quitsmoke.VO.ViewHistoryVO;
import com.cysnake.quitsmoke.tools.FormatTools;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class ViewHistoryDao extends BaseDao {

	public static final String TABLE_NAME = "view_history";
	public static final String KEY_COUNT = "coun";
	public static final String KEY_DATE = "thedate";

	private static final String TAG = "ViewHistoryDao";
	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;
	private final Context mCtx;

	public ViewHistoryDao(Context ctx) {
		this.mCtx = ctx;
	}

	public ViewHistoryDao open() throws SQLException {
		mDbHelper = new DatabaseHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	public ArrayList<ViewHistoryVO> getAll() {
		Cursor cursor = mDb.query(TABLE_NAME, new String[] { KEY_COUNT,
				KEY_DATE }, null, null, null,null, null);
//		Cursor cursor=mDb.rawQuery("select * from view_history", null);
		return changeCursor(cursor);

	}

	private ArrayList<ViewHistoryVO> changeCursor(Cursor cursor) {
		ArrayList<ViewHistoryVO> list = new ArrayList<ViewHistoryVO>();
		while (cursor.moveToNext()) {
			ViewHistoryVO viewHistory = new ViewHistoryVO();
			int temp = cursor.getColumnIndex(KEY_COUNT);
			viewHistory.setNumber((cursor.getInt(temp)));
			temp = cursor.getColumnIndex(KEY_DATE);
			try {
				if (cursor.getString(temp) != null) {
					viewHistory.setDate(FormatTools.stringToDate(cursor
							.getString(temp)));
				} else {
					viewHistory.setDate(null);
				}

			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			list.add(viewHistory);
		}
		return list;
	}
}
